package juc.c_021_02Interview;
/*
   Talk is cheap. Show me the code.
 */

import java.util.LinkedList;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description
 * @Date 2021/6/26
 * @Author liudl
 */
public class MyContainer2<T> {
    final private LinkedList<T> lists = new LinkedList<>();
    private int count = 0;
    private final Lock lock = new ReentrantLock();
    private final Condition producer = lock.newCondition();
    private final Condition consumer = lock.newCondition();

    public void put(T t) {
        lock.lock();
        try {
            final int MAX = 10;
            while (lists.size() == MAX) {
                try {
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            lists.add(t);
            ++count;
            consumer.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public T get() {
        T t = null;
        lock.lock();
        try {
            while (lists.size() == 0) {
                consumer.await();
            }
            t = lists.removeFirst();
            count--;
            producer.signalAll(); //通知生产者进行生产
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
        return t;
    }

    public static void main(String[] args) {
        MyContainer2<String> c = new MyContainer2<>();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int i1 = 0; i1 < 5; i1++) {
                    System.out.println(Thread.currentThread().getName() + "  " + c.get());
                }
            }, "c" + i).start();
        }
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int i1 = 0; i1 < 25; i1++) {
                    c.put(Thread.currentThread().getName() + "  " + i1);
                }
            }, "p" + i).start();
        }
    }

}
